import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class CSVReader {
	protected BufferedReader filereader;
	protected ArrayList<String> keyTable;
	String filename;

	public CSVReader(String filename) throws FileNotFoundException{
		this.filereader = new BufferedReader(new FileReader(new File(filename)));
		this.filename = filename;
	}

	public CSVReader(File f) throws FileNotFoundException {
		this.filereader = new BufferedReader(new FileReader(f));
		this.filename = f.getAbsolutePath();
	}

	public boolean hasNext() throws IOException {
		return this.filereader.ready();
	}

	public void reset() throws WTFException {
		try {
			this.filereader.close();
			this.filereader = new BufferedReader(new FileReader(new File(filename)));
			this.keyTable = new ArrayList<String>();
			
			try {
				String line = this.filereader.readLine();
				String[] values_in_line = line.split(",");
				for ( int i = 0; i < values_in_line.length; ++i ) {
					this.keyTable.add(values_in_line[i]);
				}
			} catch (IOException e) {
				System.err.println("Oh snaps, error reading in the key");
				throw new WTFException();
			}			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ArrayList<String> getNextLine() {
		ArrayList<String> ret = new ArrayList<String>();
		
		try {
			String line = this.filereader.readLine();
			String[] values_in_line = line.split(",");
			for ( int i = 0; i < values_in_line.length; ++i ) {
				ret.add(values_in_line[i]);
			}
		} catch (IOException e) {
			System.err.println("Oh snaps, error reading our file.");
			System.err.println("Moving past this line. Trying to suck it up.");
		}
		return ret;
	}
	
	public ArrayList<Statistic> getNextStatLine() {
		ArrayList<Statistic> ret = new ArrayList<Statistic>();
		
		try {
			String line = this.filereader.readLine();
			String[] values_in_line = line.split(",");
			for ( int i = 0; i < values_in_line.length; ++i ) {
				Statistic n = new Statistic();
				n.name  = this.keyTable.get(i);
				n.value = values_in_line[i];
				ret.add(n);
			}
		} catch (IOException e) {
			System.err.println("Oh snaps, error reading our file.");
			System.err.println("Moving past this line. Trying to suck it up.");
		}
		return ret;
	}

	public int getWidth() throws IOException, WTFException {
		this.reset();
		ArrayList<String> s = null;
		if ( this.hasNext() )
			s = this.getNextLine();
		if ( s != null )
			return s.size();
		return -1;
	}

}
